package io.zhengsh.juc._0volatile1;

import java.util.ArrayList;
import java.util.List;

/**
 * volatile 并不能保证多个线程共同修改 running 变量时所带来的不一致的问题，
 * 也就是说 volatile 不能保证替代 synchronized
 */
public class Volatile_01 {

    volatile int count = 0;

    // 解决线程不安全方案增加 synchronized
    /* synchronized */
    void m() {
        for (int i = 0; i < 10000; i++) {
            count++;
        }
    }

    public static void main(String[] args) {
        Volatile_01 v01 = new Volatile_01();

        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(v01::m, "Thread-" + i));
        }

        threads.forEach(Thread::start);

        threads.forEach(item -> {
            try {
                item.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println(v01.count);
    }
}
